//
//  ByUserDataVC.m
//  caipiao_ios
//
//  Created by mc on 2018/7/11.
//  Copyright © 2018年 ZhangZhanbin. All rights reserved.
//

#import "ByUserDataVC.h"
#import "ByUserChangeNickNameVC.h"
#import "ByUserChangePhoneVC.h"
#import "ByUserPerfectDataVC.h"

@interface ByUserDataVC ()<UITableViewDelegate,UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *iconView;

@end

@implementation ByUserDataVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"个人资料";
    
    [self addLeftBackBarButtonItem];
    
    [self initViews];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    [self performSelector:@selector(reloadViews) withObject:nil afterDelay:0.2];
}


- (void)reloadViews{
    [self.tableView reloadData];
}

- (void)initViews{
    self.view.backgroundColor = BY_BACKGROUND_COLOR;
    self.tableView = [[UITableView alloc] init];
    self.tableView.backgroundColor = BY_BACKGROUND_COLOR;
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(0);
        if (@available(ios 11.0,*)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(0);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(0);
        } else {
            make.top.equalTo(self.view).offset(0);
            make.bottom.equalTo(self.view).offset(0);
        }
    }];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 2;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        UILabel *line = [[UILabel alloc] init];
        [cell addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cell).offset(0);
            make.right.equalTo(cell).offset(0);
            make.bottom.equalTo(cell).offset(0);
            make.height.mas_equalTo(@1);
        }];
        line.backgroundColor = BY_LINE_COLOR;
    }
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    
    UILabel *titleLabel = [[UILabel alloc] init];
    [cell.contentView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(cell.contentView).offset(10);
        make.centerY.equalTo(cell.contentView).offset(0);
        make.size.mas_equalTo(CGSizeMake(120, 20));
    }];
    
    titleLabel.font = FONT(14);
    titleLabel.textColor = [UIColor blackColor];
    
    if (indexPath.section == 0 &&  indexPath.row == 0) {
        
        titleLabel.text = @"头像";
        UIImageView *iconView = [[UIImageView alloc] init];
        [cell.contentView addSubview:iconView];
        [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(cell.contentView).offset(-20);
            make.centerY.equalTo(cell.contentView).offset(0);
            make.size.mas_equalTo(CGSizeMake(60, 60));
        }];
        iconView.layer.cornerRadius = 30;
        iconView.layer.masksToBounds = YES;
        [iconView sd_setImageWithURL:[NSURL URLWithString:BY_USER.head_pic] placeholderImage:HEAD_ICOM_IMAGE];
        iconView.userInteractionEnabled = YES;
        self.iconView = iconView;
    
    }else{
        
        UILabel *valueLabel = [[UILabel alloc] init];
        [cell.contentView addSubview:valueLabel];
        [valueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(titleLabel.mas_right).offset(20);
            make.right.equalTo(cell.contentView).offset(-20);
            make.centerY.equalTo(cell.contentView).offset(0);
            make.height.mas_equalTo(@20);
        }];
        valueLabel.textColor = [UIColor lightGrayColor];
        valueLabel.textAlignment = NSTextAlignmentRight;
        valueLabel.font = FONT(14);
        if (indexPath.section == 0 && indexPath.row == 1) {
            titleLabel.text = @"昵称";
            valueLabel.text = BY_USER.nickname;
        }else{
            titleLabel.text = @"修改手机号";
            valueLabel.text = BY_USER.mobile;
        }
    }

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 80;
    }
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 && indexPath.row == 1){
        
        ByUserChangeNickNameVC *vc = [[ByUserChangeNickNameVC alloc] init];
        [self by_normalPush:vc hasNavi:YES];
    }else if (indexPath.section == 1 && indexPath.row == 0){
        

        if (BY_USER.mobile.length > 0) {
            
            ByUserChangePhoneVC *vc = [[ByUserChangePhoneVC alloc] init];
            [self by_normalPush:vc hasNavi:YES];
            
        }else{
            ByUserPerfectDataVC *vc = [[ByUserPerfectDataVC alloc] init];
            [self by_normalPush:vc hasNavi:YES];
            
        }
        
    }else if (indexPath.section == 0 && indexPath.row == 0){
        
        
        // 创建ActionSheet
        NSString *albumButtonTitle = @"从相册中选择";
        NSString *cameraButtonTitle = @"拍照";
        NSString *cancelButtonTitle = @"取消";
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        // 添加点击动作
        // 取消
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:nil];
        // 相册中
        UIAlertAction *albumAction = [UIAlertAction actionWithTitle:albumButtonTitle style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action)
                                      {
                                          [self _choosePhotoFromAlbum];
                                      }];
        // 拍照
        UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:cameraButtonTitle style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action)
                                       {
                                           [self _getphotoFromCamera];
                                       }];
        
        // Add the actions.
        [alertController addAction:cancelAction];
        [alertController addAction:albumAction];
        [alertController addAction:cameraAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
    
}

#pragma mark - UIActionSheet代理方法（适配iOS8.0以下时使用）
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    // 从相册中选择
    if (buttonIndex == 0) {
        [self _choosePhotoFromAlbum];
    }
    // 通过拍照获取
    else if (buttonIndex == 1) {
        [self _getphotoFromCamera];
    }
}
#pragma mark - 头像图片选择相关操作
// 从相册中选择照片
- (void)_choosePhotoFromAlbum {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        
        [ByCoreToolAlert showFailureWithText:@"相册不可用!"];
        return;
    }
    [self _changeToPickerController:sourceType];
}

// 通过拍照获取照片
- (void)_getphotoFromCamera {
    
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if (![UIImagePickerController isSourceTypeAvailable:sourceType]) {
        
        [ByCoreToolAlert showFailureWithText:@"相册不可用!"];
        return;
    }
    [self _changeToPickerController:sourceType];
}


// 创建并跳转到图片获取界面
- (void)_changeToPickerController:(UIImagePickerControllerSourceType)sourceType {
    // 创建图片拾取界面
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.delegate = self;
    // 设置可编辑
    pickerController.allowsEditing = YES;
    pickerController.sourceType = sourceType;
    pickerController.title = @"头像选择";
    [pickerController.navigationBar setTintColor:BY_THEME_COLOR];
    pickerController.navigationBar.translucent = false;
    [self presentViewController:pickerController animated:YES completion:nil];
}

// UIImagePickerController代理方法，选取图片之后处理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    UIImage *editedImage = (UIImage *)[info objectForKey:UIImagePickerControllerEditedImage];
    UIImage *originalImage = (UIImage *)[info objectForKey:UIImagePickerControllerOriginalImage];
    if (editedImage) {
        // 保存到相册
        //UIImageWriteToSavedPhotosAlbum(editedImage, nil, nil, nil);
        [self dismissViewControllerAnimated:YES completion:^{
            [self UploadAvatar:editedImage];
        }];
      
        
    }
    else if (originalImage) {
      
        [self dismissViewControllerAnimated:YES completion:^{
            [self UploadAvatar:originalImage];
        }];
    }
}

- (void)UploadAvatar:(UIImage *)image{
    
    [ByCoreToolAlert showLoadind:@"头像上传中" hasMasker:YES];
    [ByApiUser userFileUploadAvatar:image success:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showSuccessWithText:@"头像更新成功"];
        
        ByModelUser *user = BY_USER;
        user.head_pic = result.data[@"data"];
        [ByCacheUser setUserInfo:user];
        [self.tableView reloadData];
        
    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
